const express = require("express");
const userRouter = require("./router/user");
const slideRouter = require("./router/slider");
const courseRouter = require("./router/course");
const sysRouter = require("./router/sys");
const musicRouter = require("./router/music");
const connection = require("./db/index");
const { expressjwt } = require("express-jwt");
const jwtConfig = require("./data/jwt");
const app = express();
const createSocket = require("./utils/socket");

app.use(express.json());

app.use(express.urlencoded({ extended: true }));

// 配置静态文静件托管
app.use(express.static("public"));

connection.connect();

// 解决跨域问题
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

//token验证中间件
app.use(
  expressjwt({ secret: jwtConfig.jwtSecret, algorithms: ["HS256"] }).unless({
    path: [/^\/api2/, /^\/music/],
  })
);

//错误级别的中间件
app.use((err, req, res, next) => {
  //token解析失败
  if (err.name === "UnauthorizedError") {
    return res.send({
      status: 401,
      message: "无效的token",
    });
  }
  res.send({
    status: 500,
    message: "服务端错误",
  });
});

createSocket(app);

app.use("/user", userRouter);
app.use("/slider", slideRouter);
app.use("/course", courseRouter);
app.use("/api2", sysRouter);
app.use("/music", musicRouter);

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
